from kubernetes import client,config
from django.shortcuts import redirect
from datetime import date,timedelta
import os
#登录认证检查
proto = "https://"
port = "6443"
IP = proto + os.environ.get("MasterIP")+":"+port
def auth_check(auth_type,kstr):
    if auth_type == "token":
        token = kstr
        configuration = client.Configuration()
        configuration.host = IP
        #configuration.host = "https://192.168.75.80:6443"
        configuration.ssl_ca_cert = r"%s" %(os.path.join('kubeconfig',"ca.crt"))
        configuration.verify_ssl = True  # 启用证书
        # token = " eyJhbGciOiJSUzI1NiIsImtpZCI6ImpGZVNLa3JoSWpQbFBCaHM4NTdlV2FUNUN6Q3EzbUw2VzdCamkzSmgxUW8ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tMnFsYzQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYmMzODFlYmEtZjdhYy00NDBmLTllMDYtNzUwMjVjM2YwNzkzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.UMQg_1Xsrkty_udel3jD64Nf-0A_Pj2wA3MnMrx_T5PnUAvkQg2eKkhyy4esuAs6ho-3zn_3TQylByrI72_EHTfEXjkIcqw00oPxtuVkE8NhjEuXEMob-oko72tYtQRLvhoHE_-XJBBfmS7cMOnv5XieUeZMSHjqPEo35vK59xzNOceRXf3gk91x-Fac6TzthKfr316z5geJ1cPVnZSVjl1QK54Cm6HfZLLESKsOcIjjiykUYFG_b-YPs9OqNkL4MYFxG6pMzQvtkiYgSgnmHKaGMt-SnstiOg_PLHF5qTzNcydhBUbG7W0BTW9P9zQeICdXemKUAjsp9FTrtvTLzw"
        configuration.api_key = {"authorization": "Bearer" + token}
        client.Configuration.set_default(configuration)
        try:
            core_api = client.CoreApi()
            core_api.get_api_versions()  # 测试链接k8是否成功
            return True
        except Exception:
            return False
    elif auth_type == "kubeconfig":
        random_str = kstr
        file_path = os.path.join('kubeconfig', random_str)
        config.load_kube_config(r"%s" % file_path)
        try:
            core_api = client.CoreApi()
            core_api.get_api_versions()  # 测试链接k8是否成功
            return True
        except Exception:
            return False
#登录状态装饰器
def self_login_required(func):
    def inner(request,*args,**kwargs):
        is_login = request.session.get('is_login',False)
        if is_login:
            return func(request,*args,**kwargs)
        else:
            return redirect("/login")
    return inner

#传入登录类型加载配置
def load_auth_config(auth_type,astr):
    if auth_type == "token":
        token = astr
        configuration = client.Configuration()
        configuration.host = IP
        #configuration.host = "https://192.168.75.80:6443"
        configuration.ssl_ca_cert = r"%s" %(os.path.join('kubeconfig',"ca.crt"))
        configuration.verify_ssl = True  # 启用证书
        configuration.api_key = {"authorization": "Bearer" + token}
        client.Configuration.set_default(configuration)
    elif auth_type == "kubeconfig":
        random_str = astr
        file_path = os.path.join('kubeconfig', random_str)
        config.load_kube_config(r"%s" % file_path)

#时间统一格式化功能
def dt_format(timestamp):
    t = date.strftime(timestamp + timedelta(hours=8), "%Y-%m-%d %H:%M:%S")
    return t